import {Component, EventEmitter, Input, Output} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {FormComponentService} from "./form-component.service";
import { Geolocation } from '@ionic-native/geolocation';
declare var BMap;

/**
 * Generated class for the FormComponentPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-form-component',
  templateUrl: 'form-component.html',
})
export class FormComponentPage {
  private _account:any;
  @Output() output = new EventEmitter<any>();
  @Input() locate : boolean = false;
  accountForm: FormGroup;
  public map: any;
  public address: any = "正在获取当前位置...";

  constructor(public navCtrl: NavController, public navParams: NavParams,public fb: FormBuilder,public serv:FormComponentService,private geolocation: Geolocation) {
    let data = this.account;
    this.accountForm = this.serv.group;

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FormComponentPage');
  }
  @Input()
  set location(val:boolean){
    this.locate = val;
    if (this.locate){
      this.setAddress();
    }
  }

  @Input()
  set account(val:any){
    this._account = val;
  }

  _submitForm(){
    this.output.emit(this.accountForm.value);
  }

  setAddress(){
    // navigator.geolocation.getCurrentPosition(bp=>{
    //   let ggPoint = new BMap.Point(bp.coords.longitude,bp.coords.latitude);
    //   BMap.Convertor.translate(ggPoint, 0,position=> {
    //     var gc = new BMap.Geocoder();
    //     gc.getLocation(position, rs=>{
    //       var addComp = rs.addressComponents;
    //       this.address =  addComp.province +  addComp.city + addComp.district + addComp.street + addComp.streetNumber;//获取地址
    //       this.accountForm.patchValue({ addr: this.address });
    //
    //     });
    //   });
    // });
    this.geolocation.getCurrentPosition().then((resp) => {
      // let ggPoint = new BMap.Point(resp.coords.longitude,resp.coords.latitude);
      let ggPoint = new BMap.Point(resp.coords.longitude,resp.coords.latitude);
      BMap.Convertor.translate(ggPoint, 0,position=> {
        var gc = new BMap.Geocoder();
        gc.getLocation(position, rs=>{
          var addComp = rs.addressComponents;
          this.address =  addComp.province +  addComp.city + addComp.district + addComp.street + addComp.streetNumber;//获取地址
          this.accountForm.patchValue({ addr: this.address });
          this.accountForm.patchValue({ note2: resp.coords.longitude + '||' + resp.coords.latitude});
        });
      });
    }).catch((error) => {
      this.accountForm.patchValue({ addr: '定位失败,请手动填写' });
      this.accountForm.patchValue({ note2: '0'});
    });
  }

  showAll(){
    console.log(this.accountForm.value);
  }


}
